package com.chookss.home.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.GalleryListEntity;
import com.chookss.home.gallery.adapter.GalleryAdapter;
import com.chookss.home.gallery.adapter.GalleryListAdapter;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.SelectDialogListener;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class GalleryListActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.rvListView)
    RecyclerView rvListView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    @BindView(R.id.ll_type)
    LinearLayout ll_type;
    private GalleryAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private String searchType = "1";//  搜索类型 1-日期 2-标签 3 地点 默认值为1
    private int currentType=1;//  搜索类型 1-日期 2-标签 3 地点 默认值为1
    private int currentIndex=0;//  搜索类型 1-日期 2-标签 3 地点 默认值为1
    private int endType=1;//  搜索类型 1-日期 2-标签 3 地点 默认值为1
    private int roleType = 1; //roleType 0个人 1全部
    private String data="",tagCode="",catalogCodes="",city="",createTime="";
    private List<GalleryListEntity.ImagePathListBean> imagePathListBeanList = new ArrayList<>();
    private GalleryListAdapter listAdapter;
    private List<GalleryListEntity> galleryListEntityList = new ArrayList<>();
    private View emptyView,emptyListView;
    private TextView tvEmpty,tvEmpty2,tvListEmpty,tvListEmpty2;//空布局;
    private BottomListsDialog bottomListsDialog = null;
    private List<String> dialogList = new ArrayList<>();
    private String cacheName="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_gallery_list);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        data = getIntent().getStringExtra("data");
        tagCode = getIntent().getStringExtra("tagCode");
        city = getIntent().getStringExtra("city");
        createTime = getIntent().getStringExtra("createTime");
        catalogCodes = getIntent().getStringExtra("catalogCodes");
        searchType = getIntent().getStringExtra("searchType");
        KLog.i("------"+searchType);
        String []types=searchType.split(",");
        currentType=Utils.changeNumber(types[types.length-1]);
        endType=Utils.changeNumber(types[types.length-1]);
        roleType = getIntent().getIntExtra("roleType", 1);
        if(currentType==3){
            if(Utils.isNull(city)){
                commonTitleTxt.setText("未知");
            }else{
                if(city.equals("a")){
                    commonTitleTxt.setText("未知");
                }else{
                    commonTitleTxt.setText(city);
                }
            }
        }else{
            commonTitleTxt.setText(data);
        }

        dialogList.add("日期");
        dialogList.add("标签");
        dialogList.add("地点");
        dialogList.add("取消");
        if(types.length>1){
            if(types[0].equals("1")){
                dialogList.remove(0);
            }else if(types[0].equals("2")){
                dialogList.remove(1);
            }else if(types[0].equals("3")){
                dialogList.remove(2);
            }

            if(currentType==1){
                cacheName="日期";
            }else if(currentType==2){
                cacheName="标签";
            }else if(currentType==3){
                cacheName="地点";
            }
            for (int i = 0; i <dialogList.size() ; i++) {
                if(dialogList.get(i).equals(cacheName)){
                    currentIndex=i;
                }
            }
        }

        bottomListsDialog = new BottomListsDialog(this, dialogList, new SelectDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if(list.get(position).equals("日期")){
                    currentType=1;
                }else if(list.get(position).equals("标签")){
                    currentType=2;
                }else if(list.get(position).equals("地点")){
                    currentType=3;
                }
                smrRf.autoRefresh();
                bottomListsDialog.setSelect(position);
                bottomListsDialog.dismiss();
            }
        });
        if(types.length>1){
            bottomListsDialog.setSelect(currentIndex);
        }else{
            bottomListsDialog.setSelect(currentType-1);
        }
       if(types.length>2){
           ll_type.setVisibility(View.GONE);
       }else{
           ll_type.setVisibility(View.VISIBLE);
       }
        NavigationTools.saveUseRecord(this, "1", "26");
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(4, Utils.dip2px(this, 2), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        adapter = new GalleryAdapter(R.layout.item_gallery, this, imagePathListBeanList,1);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        //列表
        rvListView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        listAdapter = new GalleryListAdapter(R.layout.item_gallery_list, this, galleryListEntityList, searchType,roleType);
        rvListView.setAdapter(listAdapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        rvListView.setItemAnimator(null);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvEmpty = emptyView.findViewById(R.id.tvEmpty);
        tvEmpty2 = emptyView.findViewById(R.id.tvEmpty2);
        emptyListView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, rvListView, false);
        tvListEmpty = emptyListView.findViewById(R.id.tvEmpty);
        tvListEmpty2 = emptyListView.findViewById(R.id.tvEmpty2);
        if(roleType==1){
            tvEmpty.setText("暂无数据");
            tvListEmpty.setText("暂无数据");
        }else{
            tvEmpty.setText("图库暂时还是空的");
            tvEmpty2.setText("块去发布你的第一张图片吧");
        }
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    if(types.length>1){
                        if(endType==currentType){
                            //当前类型与之前一样，则选择更多列表
                            getData();
                        }else{
                            getListData();
                        }
                    }else{
                        if(searchType.contains(currentType+"")){
                            //当前类型与之前一样，则选择更多列表
                            getData();
                        }else{
                            getListData();
                        }
                    }

                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                if(types.length>1){
                    if(endType==currentType){
                        //当前类型与之前一样，则选择更多列表
                        getData();
                    }else{
                        getListData();
                    }
                }else{
                    if(searchType.contains(currentType+"")){
                        //当前类型与之前一样，则选择更多列表
                        getData();
                    }else{
                        getListData();
                    }
                }
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
//        allmap.put("searchType", searchType + "");
        if(!Utils.isNull(createTime)){
            allmap.put("createTime", createTime);
        }
        if(!Utils.isNull(tagCode)){
            allmap.put("tagCode", tagCode);
        }
        if(!Utils.isNull(city)){
            allmap.put("city", city);
        }
        if(!Utils.isNull(catalogCodes)){
            allmap.put("catalogCodes", catalogCodes);
        }
        allmap.put("pageNum", currentPage + "");
        allmap.put("roleType", roleType + "");
        allmap.put("pageSize", "40");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<GalleryListEntity.ImagePathListBean>>>() {
        }.getType(), null, Urls.selectAppImageMoreList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<GalleryListEntity.ImagePathListBean>>() {
            @Override
            public void onSuccess(List<GalleryListEntity.ImagePathListBean> data) {
                if (currentPage == 1) {
                    imagePathListBeanList.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                int oldIndex = imagePathListBeanList.size();
                recyclerView.setVisibility(View.VISIBLE);
                rvListView.setVisibility(View.GONE);
                if (data != null && data.size() > 0) {
                    imagePathListBeanList.addAll(data);
                    if (currentPage == 1) {
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter.notifyItemRangeChanged(oldIndex, data.size());
                    }
                } else {
                    isEnd = true;
                    if (imagePathListBeanList.size() == 0) {
                        listAdapter.setEmptyView(emptyView);
                    }

                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getListData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        map.put("roleType", roleType+"");
        map.put("searchType", currentType+"");
        if(!Utils.isNull(createTime)){
            map.put("createTime", createTime);
        }
        if(!Utils.isNull(tagCode)){
            map.put("tagCode", tagCode);
        }
        if(!Utils.isNull(city)){
            map.put("city", city);
        }
        if(!Utils.isNull(catalogCodes)){
            map.put("catalogCodes", catalogCodes);
        }
        KLog.i(currentType+"=="+searchType+","+(currentType+""));
        listAdapter.setType(currentType,searchType+","+(currentType+""),catalogCodes,city,createTime,tagCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<GalleryListEntity>>>() {
        }.getType(), null, Urls.selectAppImageList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<GalleryListEntity>>() {
            @Override
            public void onSuccess(List<GalleryListEntity> data) {
                recyclerView.setVisibility(View.GONE);
                rvListView.setVisibility(View.VISIBLE);
                if (currentPage == 1) {
                    galleryListEntityList.clear();
                    listAdapter.notifyDataSetChanged();
                }
                if (data != null && data.size() > 0) {
                    galleryListEntityList.addAll(data);
                    listAdapter.notifyDataSetChanged();
                } else {
                    isEnd = true;
                    if (galleryListEntityList.size() == 0) {
                        listAdapter.setEmptyView(emptyListView);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }
    @OnClick({R.id.common_title_back, R.id.ll_type})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.ll_type:
                if(bottomListsDialog!=null){
                    bottomListsDialog.show();
                }
                break;

        }
    }


    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

}
